<template>
  <div class="app-container">
    <!-- 1. 优化的搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 假设后端支持按用户名和文章标题进行模糊搜索 -->
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文章标题" prop="articleTitle">
        <el-input
          v-model="queryParams.articleTitle"
          placeholder="请输入文章标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:collect:add']"
        >新增收藏</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:collect:remove']"
        >批量取消</el-button>
      </el-col>
       <!-- 通常收藏记录不提供修改，只提供删除（取消收藏），故隐藏修改和导出按钮 -->
      <!--
      <el-col :span="1.5">
        <el-button type="success" plain ...>修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain ...>导出</el-button>
      </el-col>
      -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 2. 优化的数据表格 -->
    <el-table v-loading="loading" :data="collectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="收藏ID" align="center" prop="id" />
      <!-- 直接显示关联表的名称，而不是ID -->
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="收藏的文章" align="center" prop="articleTitle" :show-overflow-tooltip="true" />
      <el-table-column label="收藏时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:collect:remove']"
          >取消收藏</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 3. 优化的添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 使用可搜索的下拉框来选择用户和文章 -->
        <el-form-item label="选择用户" prop="userId">
          <el-select v-model="form.userId" filterable remote placeholder="请输入用户名搜索" :remote-method="searchUsers" :loading="userLoading">
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择文章" prop="articleId">
           <el-select v-model="form.articleId" filterable remote placeholder="请输入文章标题搜索" :remote-method="searchArticles" :loading="articleLoading">
            <el-option
              v-for="item in articleOptions"
              :key="item.articleId"
              :label="item.articleTitle"
              :value="item.articleId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCollect, getCollect, delCollect, addCollect, updateCollect } from "@/api/iot/articleCollect";
// 假设您有查询用户和文章列表的API
import { listUser } from "@/api/system/user"; // 请替换为实际的用户API
import { listArticle } from "@/api/iot/article"; // 请替换为实际的文章API

export default {
  name: "Collect",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      total: 0,
      collectList: [],
      title: "",
      open: false,
      // 用户和文章选择框的加载状态和选项
      userLoading: false,
      articleLoading: false,
      userOptions: [],
      articleOptions: [],
      // 查询参数（已优化）
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        articleTitle: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "必须选择一个用户", trigger: "change" }
        ],
        articleId: [
          { required: true, message: "必须选择一篇文章", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询文章收藏列表 */
    getList() {
      this.loading = true;
      listCollect(this.queryParams).then(response => {

        this.collectList = response.rows.map(item => {
            if (item.createTime) item.createTime = item.createTime * 1000;
            return item;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        articleId: null,
      };
      this.userOptions = [];
      this.articleOptions = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章收藏";
    },
    /** 修改按钮操作 (通常不使用，已从UI移除) */
    handleUpdate(row) {
      // ...
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 收藏记录通常没有修改，只有新增
          addCollect(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认取消编号为"' + ids + '"的收藏记录？').then(function() {
        return delCollect(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("取消成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 (通常不使用，已从UI移除) */
    handleExport() {
      // ...
    },

    /** 远程搜索用户列表 */
    searchUsers(query) {
      if (query !== '') {
        this.userLoading = true;
        listUser({ userName: query }).then(response => {
          this.userOptions = response.rows;
          this.userLoading = false;
        });
      } else {
        this.userOptions = [];
      }
    },
    /** 远程搜索文章列表 */
    searchArticles(query) {
      if (query !== '') {
        this.articleLoading = true;
        listArticle({ title: query }).then(response => {
          // 后端返回的文章对象需要包含 articleId 和 articleTitle
          this.articleOptions = response.rows;
          this.articleLoading = false;
        });
      } else {
        this.articleOptions = [];
      }
    }
  }
};
</script>
